//
//  UpLoadIconController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/2.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

class UpLoadIconController: BaseViewController {
    
    var urlStr : String = "-999"
    
    var hiddenBar = true
    
    
    private var userContentController : WKUserContentController?
    
    fileprivate lazy var webView : WKWebView = {
        
        let config = WKWebViewConfiguration()
        
        let userVC = WKUserContentController()
        
        self.userContentController = userVC
        
        config.userContentController = userVC
        
        
        let webView1 = WKWebView(frame: UIScreen.main.bounds, configuration: config)
        
        
        let delegateVC = WKDelegateController()
        
        delegateVC.delegate = self
        
        config.userContentController.add(delegateVC, name: "sendMessage")
        
        webView1.navigationDelegate = self
        
        
        return webView1
    }()
    
    
    override func loadView() {
        
        
        view = webView
        
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        automaticallyAdjustsScrollViewInsets = !hiddenBar
        
        navigationController?.setNavigationBarHidden(hiddenBar, animated: true)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        
        webView.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
        
        
        
        SVProgressHUD.show(withStatus: "正在加载数据...")
        
        
        //        1.发送请求
        if urlStr.contains("?") {
            
            if UserViewModel.shared.userIsLogin() == true {
                
                urlStr = "\(urlStr)&ios_key=\(UserViewModel.shared.key ?? "")"
            }
            
        } else {
            
            if UserViewModel.shared.userIsLogin() == true {
                
                urlStr = "\(urlStr)?ios_key=\(UserViewModel.shared.key ?? "")"
            }
            
        }
        
        QL1(urlStr)
        
        
        let url = URL(string: urlStr)
        
        if let temp = url {
            
            
            let request = URLRequest(url: temp)
            
            webView.load(request)
            
            
        }
        
        
        
        
        
        
        
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
    deinit {
        
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
        webView.removeObserver(self, forKeyPath: "title")
        
        guard let temp = userContentController else {
            
            return
        }
        
        temp.removeScriptMessageHandler(forName: "sendMessage")
        
        
        QL1("------")
        
    }
    
    

}




// MARK:- KVC键值观察
extension UpLoadIconController{
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?){
        
        
        navigationItem.title = webView.title
        
        
    }
    
    
}







extension UpLoadIconController:WKDelegateControllerDelegate,WKNavigationDelegate{
    
    //js调用oc
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage){
        
        if message.body is Array<String> {
            
            let temp = message.body as! Array<String>
            
            let type = Int(temp[0])
            
            if type == 2 {
                
                navigationController?.popViewController(animated: true)
                
            }
            
        }
        
    }
    
    
    //发送请求前，决定是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void){
        
        decisionHandler(.allow);
        
    }
    
    
    //页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
        
        
        
        
    }
    
    
    //收到响应后，决定是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void){
        
        //        QL1(navigationResponse.response.url)
        
        decisionHandler(.allow);
        
        
    }
    
    
    //内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        
        
        
        
    }
    
    //OC调JS方法
    //页面加载完成后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        
        SVProgressHUD.dismiss()
        webView.evaluateJavaScript("say()") { (result, error) in
            
            //                        print(result)
            
        }
        
    }
    
    
    //页面加载失败后调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error){
        SVProgressHUD.dismiss()
        
        //        QL1(88888)
        
    }
    
    
    
    
    
}



